#include <iostream>
#include <algorithm>
using namespace std;
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* newhead = NULL, * tail = NULL;
    struct ListNode* cur = head;
    while (cur) {
        if (cur->val != val) {
            if (tail == NULL) {
                newhead = tail = cur;
            }
            else {
                tail->next = cur;
                tail = tail->next;
            }
            cur = cur->next;
        }
        else {
            struct ListNode* del = cur->next;
            free(cur);
            cur = del;
        }
    }
    if (tail) {
        tail->next = NULL;
    }
    return newhead;
}